﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Utility;
using JFnetcore.Models;
using System.Text;
using Services.IService;
using Models;
using System.Linq.Expressions;
using static Utility.EnumUtil;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace JFnetcore.Controllers
{
    public class UsersController : BaseController
    {
        private IUsersService _userService;
        private IRoleService _roleService;
        private IRolemenuService _rolemenuService;
        private IMenuService _menuService;
        private ILogService _logService;
        private IVusersService _vusersService;
        private IVmenuService _vmenuService;
        private IVlogService _vlogService;
        public UsersController(IUsersService userService,
            IRoleService roleService,
            IRolemenuService rolemenuService,
            ILogService logService,
            IMenuService menuService,
            IVusersService vusersService,
            IVmenuService vmenuService,
            IVlogService vlogService)
        {
            _userService = userService;
            _roleService = roleService;
            _rolemenuService = rolemenuService;
            _menuService = menuService;
            _logService = logService;
            _vusersService = vusersService;
            _vmenuService = vmenuService;
            _vlogService = vlogService;
        }

        #region 个人中心

        #region 修改密码
        /// <summary>
        /// 打开密码修改视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Password()
        {
            SessionModel model = getUserSession();
            if (model != null)
            {
                ViewBag.id = model.User.Id.ToString();
                ViewBag.username = model.User.User_name;
                ViewBag.loginname = model.User.Login_name;
                return View();
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 表单提交 修改密码接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ChangePassword(PasswordModel model)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                UsersModel u = getUserSession().User;
                if (u.Id.ToString() != model.UserId)
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "修改密码失败，信息传递错误！", "", "", "", false, "", ""));
                }
                else
                {
                    if (u.User_pwd != CommonUtil.Md5(model.OldPassword))
                    {
                        return Content(ReturnJsonHelp.BJUIajaxJson(300, "修改密码失败，原密码错误！", "", "", "", false, "", ""));
                    }
                    else
                    {
                        u.User_pwd = CommonUtil.Md5(model.NewPassword);
                        u.Createtime = DateTime.Now;
                        if (_userService.Update(u))
                        {
                            HttpContext.Session.Remove("CurrentUser");

                            Expression<Func<RolemenuModel, bool>> where = LinqUtil.True<RolemenuModel>();
                            where = where.AndAlso(i => i.Role_Id == u.Role_id);
                            List<RolemenuModel> list = _rolemenuService.GetList(where);
                            SessionModel smodel = new SessionModel();
                            smodel.IP = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                            smodel.User = u;
                            smodel.RolemenuList = list;
                            HttpContext.Session.Set("CurrentUser", ByteConvertHelper.Object2Bytes(smodel));
                            _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)EnumUtil.OperationEnum.update, "修改密码");
                            return Content(ReturnJsonHelp.BJUIajaxJson(200, "修改密码成功！", "", "", "", true, "", ""));
                        }
                        else
                        {
                            return Content(ReturnJsonHelp.BJUIajaxJson(300, "修改密码失败！", "", "", "", false, "", ""));
                        }
                    }
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }
        #endregion

        #region 个人记录
        /// <summary>
        /// 打开个人记录视图
        /// </summary>
        /// <param name="pagemodel"></param>
        /// <returns></returns>
        public IActionResult Myloglist(PageModel pagemodel)
        {
            //获取Session信息并且返回前台
            SessionModel userSession = getUserSession();
            if (userSession != null)
            {
                if (string.IsNullOrEmpty(pagemodel.PageCurrent))
                    pagemodel.PageCurrent = "1";
                if (string.IsNullOrEmpty(pagemodel.PageSize))
                    pagemodel.PageSize = "30";
                ViewBag.SearchKeyWords = pagemodel.SearchKeyWords;
                ViewBag.PageSize = pagemodel.PageSize;
                ViewBag.PageCurrent = pagemodel.PageCurrent;
                ViewBag.OrderField = pagemodel.OrderField;
                ViewBag.OrderDirection = pagemodel.OrderDirection;

                Expression<Func<LogModel, bool>> where = LinqUtil.True<LogModel>();
                where = where.AndAlso(i => (i.Log_ip.Contains(pagemodel.SearchKeyWords) || i.Log_remark.Contains(pagemodel.SearchKeyWords) || i.Createtime.ToString("yyyy-MM-dd HH:mm:ss").Contains(pagemodel.SearchKeyWords)) && i.Log_userid == userSession.User.Id.ToString());
                ViewBag.AllRecords = _logService.GetList(where).Count;
                ViewBag.Modellist = _logService.GetPageList(where, int.Parse(pagemodel.PageCurrent), int.Parse(pagemodel.PageSize), pagemodel.OrderField);
                return View();
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }
        #endregion

        #endregion

        #region 用户中心

        #region 用户管理
        /// <summary>
        /// 打开用户视图，用户列表
        /// </summary>
        /// <param name="pagemodel"></param>
        /// <returns></returns>
        public IActionResult Index(PageModel pagemodel)
        {
            //获取Session信息并且返回前台
            SessionModel userSession = getUserSession();
            if (userSession != null)
            {
                ViewBag.myid = userSession.User.Id.ToString();
                if (string.IsNullOrEmpty(pagemodel.PageCurrent))
                    pagemodel.PageCurrent = "1";
                if (string.IsNullOrEmpty(pagemodel.PageSize))
                    pagemodel.PageSize = "30";
                ViewBag.SearchKeyWords = pagemodel.SearchKeyWords;
                ViewBag.PageSize = pagemodel.PageSize;
                ViewBag.PageCurrent = pagemodel.PageCurrent;
                ViewBag.OrderField = pagemodel.OrderField;
                ViewBag.OrderDirection = pagemodel.OrderDirection;

                Expression<Func<VusersModel, bool>> where = LinqUtil.True<VusersModel>();
                where = where.AndAlso(i => i.Login_name.Contains(pagemodel.SearchKeyWords) || i.User_name.Contains(pagemodel.SearchKeyWords) || i.User_email.Contains(pagemodel.SearchKeyWords));
                ViewBag.AllRecords = _vusersService.GetList(where).Count;
                ViewBag.Modellist = _vusersService.GetPageList(where, int.Parse(pagemodel.PageCurrent), int.Parse(pagemodel.PageSize), pagemodel.OrderField);
                return View();
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 打开用户编辑视图，添加修改用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Edit(string id)
        {
            SessionModel userSession = getUserSession();
            if (userSession != null)
            {
                if (string.IsNullOrEmpty(id))
                {
                    return View();
                }
                else
                {
                    var model = _vusersService.GetById(Int32.Parse(id));
                    return View(model);
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));

        }

        /// <summary>
        ///表单提交用户编辑接口 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UserEdit")]
        public IActionResult UserEdit(UsersModel model)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                UsersModel u = _userService.GetByLoginname(model.Login_name);
                if (u != null && model.Id == 0)
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "提交失败,登录账号已存在！", "", "", "", true, "", ""));
                }
                else
                {
                    model.Createtime = DateTime.Now;
                    if (model.User_pwd.Substring(0, 1) != "_")
                        model.User_pwd = CommonUtil.Md5(model.User_pwd);
                    if (model.Id != 0)
                    {
                        if (_userService.Update(model))
                        {
                            _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.update, "修改用户 " + model.User_name);
                            return Content(ReturnJsonHelp.BJUIajaxJson(200, "修改用户 " + model.User_name + " 成功！", "UsersIndex", "", "", true, "", ""));
                        }
                        else
                        {
                            return Content(ReturnJsonHelp.BJUIajaxJson(300, "修改用户 " + model.User_name + " 失败！", "", "", "", false, "", ""));
                        }
                    }
                    else
                    {
                        if (_userService.Insert(model) > 0)
                        {
                            _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.add, "新增产品类型 " + model.User_name);
                            return Content(ReturnJsonHelp.BJUIajaxJson(200, "新增用户 " + model.User_name + " 成功！", "UsersIndex", "", "", true, "", ""));
                        }
                        else
                        {
                            return Content(ReturnJsonHelp.BJUIajaxJson(300, "新增用户 " + model.User_name + " 失败！", "", "", "", false, "", ""));
                        }
                    }
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 按钮提交用户删除接口
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult UserDelete(string id)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                string name = _userService.GetById(int.Parse(id)).User_name;
                if (_userService.DeleteById(int.Parse(id)))
                {
                    _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.delete, "删除用户 " + name);
                    return Content(ReturnJsonHelp.BJUIajaxJson(200, "删除成功！", "usersIndex", "", "", false, "", ""));
                }
                else
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "删除失败！", "", "", "", false, "", ""));
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 用户编辑视图，加载角色选择视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Search()
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                StringBuilder resultstr = new StringBuilder();
                List<RoleModel> list = _roleService.GetList().Where(i => i.Disable == 1).ToList();
                resultstr.Append("[");
                int y = 0;
                foreach (RoleModel a in list)
                {
                    resultstr.Append("{\"Role_id\":\"" + a.Id + "\",\"Role_name\":\"" + a.Role_name + "\"},");
                    y++;
                }
                if (y > 0)
                    resultstr.Remove(resultstr.ToString().LastIndexOf(','), 1);
                resultstr.Append("]");
                return Content(resultstr.ToString());
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }
        #endregion

        #region 菜单管理
        /// <summary>
        /// 打开菜单视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Menu()
        {
            //获取Session信息并且返回前台
            SessionModel userSession = getUserSession();

            if (userSession != null)
            {
                StringBuilder menuhtml = new StringBuilder();
                List<MenuModel> list = _menuService.GetList();
                List<MenuModel> list1 = list.Where(i => i.Parent_Id == 0).OrderBy(i => i.Menu_rank).ToList();
                foreach (MenuModel menu in list1)
                {
                    menuhtml.Append("<tr>");
                    menuhtml.Append("<td align=\"center\">" + menu.Menu_name + "</td>");
                    menuhtml.Append("<td></td>");
                    menuhtml.Append("<td></td>");
                    menuhtml.Append("<td></td>");
                    menuhtml.Append("<td></td>");
                    menuhtml.Append("<td></td>");
                    menuhtml.Append("<td align=\"center\"><a href=\"/Users/UpdateMenuRank/" + menu.Id + "/-1\" class=\"btn btn-green\" data-toggle=\"doajax\" data-icon=\"arrow-up\"></a> " + menu.Menu_rank + " <a href=\"/Users/UpdateMenuRank/" + menu.Id + "/1\" class=\"btn btn-green\" data-toggle=\"doajax\" data-icon=\"arrow-down\"></a></td>");
                    menuhtml.Append("<td></td>");
                    menuhtml.Append("<td></td>");
                    //menuhtml.Append("<td align =\"center\" >");
                    //if (menu.Disable == 1)
                    //{
                    //    menuhtml.Append("<i class=\"fa fa-check green\"></i>");
                    //}
                    //else
                    //{
                    //    menuhtml.Append("<i class=\"fa fa-close red\"></i>");
                    //}
                    //menuhtml.Append("</td>");
                    //menuhtml.Append("<td align =\"center\"><a href =\"Users/MenuEdit/"+menu.Id+"\" class=\"btn btn-green\" data-toggle=\"dialog\" data-width=\"500\" data-height=\"300\" data-id=\"UsersMenuEdit\" data-title=\"编辑 【"+menu.Menu_name+"】\">编辑</a></td>");
                    menuhtml.Append("</tr>");
                    List<MenuModel> list2 = list.Where(i => i.Parent_Id == menu.Id).OrderBy(i => i.Menu_rank).ToList();
                    foreach (MenuModel menu2 in list2)
                    {
                        menuhtml.Append("<tr>");
                        menuhtml.Append("<td></td>");
                        menuhtml.Append("<td align=\"center\">" + menu2.Menu_name + "</td>");
                        menuhtml.Append("<td></td>");
                        menuhtml.Append("<td></td>");
                        menuhtml.Append("<td></td>");
                        menuhtml.Append("<td></td>");
                        menuhtml.Append("<td></td>");
                        menuhtml.Append("<td align=\"center\"><a href=\"/Users/UpdateMenuRank/" + menu2.Id + "/-1\" class=\"btn btn-green\" data-toggle=\"doajax\" data-icon=\"arrow-up\"></a> " + menu2.Menu_rank + " <a href=\"/Users/UpdateMenuRank/" + menu2.Id + "/1\" class=\"btn btn-green\" data-toggle=\"doajax\" data-icon=\"arrow-down\"></a></td>");
                        menuhtml.Append("<td></td>");
                        //menuhtml.Append("<td align =\"center\" >");
                        //if(menu2.Disable == 1)
                        //    {
                        //    menuhtml.Append("<i class=\"fa fa-check green\"></i>");
                        //}
                        //    else
                        //    {
                        //    menuhtml.Append("<i class=\"fa fa-close red\"></i>");
                        //}
                        //menuhtml.Append("</td>");
                        //menuhtml.Append("<td align =\"center\"><a href =\"Users/MenuEdit/" + menu2.Id + "\" class=\"btn btn-green\" data-toggle=\"dialog\" data-width=\"500\" data-height=\"300\" data-id=\"UsersMenuEdit\" data-title=\"编辑 【" + menu2.Menu_name + "】\">编辑</a></td>");
                        menuhtml.Append("</tr>");
                        List<MenuModel> list3 = list.Where(i => i.Parent_Id == menu2.Id).OrderBy(i => i.Menu_rank).ToList();
                        foreach (MenuModel menu3 in list3)
                        {
                            menuhtml.Append("<tr>");
                            menuhtml.Append("<td></td>");
                            menuhtml.Append("<td></td>");
                            menuhtml.Append("<td align=\"center\">" + menu3.Menu_name + "</td>");
                            menuhtml.Append("<td align=\"center\">" + menu3.Menu_idname + "</td>");
                            menuhtml.Append("<td align=\"center\">" + menu3.Menu_url + "</td>");
                            menuhtml.Append("<td align=\"center\">" + menu3.Menu_target + "</td>");
                            menuhtml.Append("<td></td>");
                            menuhtml.Append("<td></td>");
                            menuhtml.Append("<td align=\"center\"><a href=\"/Users/UpdateMenuRank/" + menu3.Id + "/-1\" class=\"btn btn-green\" data-toggle=\"doajax\" data-icon=\"arrow-up\"></a> " + menu3.Menu_rank + " <a href=\"/Users/UpdateMenuRank/" + menu3.Id + "/1\" class=\"btn btn-green\" data-toggle=\"doajax\" data-icon=\"arrow-down\"></a></td>");
                            //menuhtml.Append("<td align =\"center\" >");
                            //if (menu3.Disable == 1)
                            //{
                            //    menuhtml.Append("<i class=\"fa fa-check green\"></i>");
                            //}
                            //else
                            //{
                            //    menuhtml.Append("<i class=\"fa fa-close red\"></i>");
                            //}
                            //menuhtml.Append("</td>");
                            //menuhtml.Append("<td align =\"center\"><a href =\"Users/MenuEdit/" + menu3.Id + "\" class=\"btn btn-green\" data-toggle=\"dialog\" data-width=\"500\" data-height=\"300\" data-id=\"UsersMenuEdit\" data-title=\"编辑 【" + menu3.Menu_name + "】\">编辑</a></td>");
                            menuhtml.Append("</tr>");

                        }
                    }
                }
                ViewBag.menuhtml = menuhtml;
                return View();

            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 修改菜单排序
        /// </summary>
        /// <param name="menuid"></param>
        /// <param name="rank"></param>
        /// <returns></returns>
        [Route("Users/UpdateMenuRank/{menuid?}/{rank?}")]
        public IActionResult UpdateMenuRank(int menuid, int rank)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                MenuModel m = _menuService.GetById(menuid);
                m.Menu_rank += rank;
                if (_menuService.Update(m))
                {
                    _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)EnumUtil.OperationEnum.update, "修改菜单顺序 menuid:" + menuid + ",rank:" + rank);
                    return Content(ReturnJsonHelp.BJUIajaxJson(200, "提交成功！", "UsersMenu", "", "", false, "", ""));
                }
                else
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "提交失败！", "", "", "", false, "", ""));
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }



        /// <summary>
        /// 打开菜单编辑视图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult MenuEdit(string id)
        {
            SessionModel userSession = getUserSession();
            if (userSession != null)
            {
                if (string.IsNullOrEmpty(id))
                {
                    return View();
                }
                else
                {
                    var model = _menuService.GetById(Int32.Parse(id));
                    return View(model);
                }
            }
            else
            {
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
            }
        }

        /// <summary>
        ///表单提交菜单编辑接口 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("EditMenu")]
        public IActionResult EditMenu(MenuModel model)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                model.Createtime = DateTime.Now;
                if (_menuService.Update(model))
                {
                    _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)EnumUtil.OperationEnum.update, "修改菜单名称");
                    return Content(ReturnJsonHelp.BJUIajaxJson(200, "提交成功！", "UsersMenu", "", "", true, "", ""));
                }
                else
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "提交失败！", "", "", "", false, "", ""));
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }
        #endregion

        #region 角色管理
        /// <summary>
        /// 打开角色视图，角色列表
        /// </summary>
        /// <param name="pagemodel"></param>
        /// <returns></returns>
        public IActionResult Role(PageModel pagemodel)
        {
            SessionModel userSession = getUserSession();

            if (userSession != null)
            {
                if (string.IsNullOrEmpty(pagemodel.PageCurrent))
                    pagemodel.PageCurrent = "1";
                if (string.IsNullOrEmpty(pagemodel.PageSize))
                    pagemodel.PageSize = "30";
                ViewBag.SearchKeyWords = pagemodel.SearchKeyWords;
                ViewBag.PageSize = pagemodel.PageSize;
                ViewBag.PageCurrent = pagemodel.PageCurrent;
                ViewBag.OrderField = pagemodel.OrderField;
                ViewBag.OrderDirection = pagemodel.OrderDirection;

                Expression<Func<RoleModel, bool>> where = LinqUtil.True<RoleModel>();
                where = where.AndAlso(i => i.Role_name.Contains(pagemodel.SearchKeyWords));
                ViewBag.AllRecords = _roleService.GetList(where).Count;
                ViewBag.Modellist = _roleService.GetPageList(where, int.Parse(pagemodel.PageCurrent), int.Parse(pagemodel.PageSize), pagemodel.OrderField);
                return View();

            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 打开角色编辑视图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult RoleEdit(string id)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                if (string.IsNullOrEmpty(id))
                {
                    return View();
                }
                else
                {
                    var model = _roleService.GetById(Int32.Parse(id));
                    return View(model);
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        ///表单提交角色编辑接口 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("EditRole")]
        public IActionResult EditRole(RoleModel model)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                if (model.Id == 1)
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "提交失败,管理员禁止修改！", "", "", "", false, "", ""));
                }
                else
                {
                    model.Createtime = DateTime.Now;
                    model.Disable = 1;
                    if (_roleService.Update(model))
                    {
                        _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)EnumUtil.OperationEnum.update, "修改角色信息 " + model.Role_name);
                        return Content(ReturnJsonHelp.BJUIajaxJson(200, "提交成功！", "UsersRole", "", "", true, "", ""));
                    }
                    else
                    {
                        return Content(ReturnJsonHelp.BJUIajaxJson(300, "提交失败！", "", "", "", false, "", ""));
                    }
                }

            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 打开角色权限视图
        /// </summary>
        /// <param name="id">roleId</param>
        /// <returns></returns>
        public IActionResult RoleMenu(string id)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                if (!string.IsNullOrEmpty(id))
                {
                    StringBuilder menuhtml = new StringBuilder();

                    List<VmenuModel> rootlist = _vmenuService.GetListByRoleidAndMenurootid(int.Parse(id), 0, 2);//获取根目录[可用]菜单,并排序
                                                                                                                //ViewBag.menuhtml = GetMenuHtml(1, rootlist, meullist);
                    foreach (VmenuModel menu in rootlist)
                    {
                        menuhtml.Append("<tr>");
                        menuhtml.Append("<td align=\"center\">" + menu.Menu_name + "</td>");
                        menuhtml.Append("<td></td>");
                        menuhtml.Append("<td></td>");
                        if (menu.Disable == 1)
                        {
                            menuhtml.Append("<td align=\"center\"><i class=\"fa fa-check green\"></i></td>");
                        }
                        else
                        {
                            menuhtml.Append("<td align=\"center\"><i class=\"fa fa-close red\"></i></td>");
                        }
                        menuhtml.Append("<td align=\"center\"><a style=\"width: 80px;\" href=\"/Users/OpenRoleMenu/" + id + "/" + menu.Id.ToString() + "/3/1\" class=\"btn btn-green\" data-toggle=\"doajax\" data-icon=\"check\" data-confirm-msg=\"确定要开通【" + menu.Menu_name + "】所有权限吗？\"></a> <a  style=\"width: 80px;\" href=\"/Users/OpenRoleMenu/" + id + "/" + menu.Id.ToString() + "/3/0\" class=\"btn btn-red\" data-toggle=\"doajax\" data-icon=\"close\" data-confirm-msg=\"确定要关闭【" + menu.Menu_name + "】所有权限吗？\"></a></td>");
                        menuhtml.Append("</tr>");
                        List<VmenuModel> rootlist2 = _vmenuService.GetListByRoleidAndMenurootid(int.Parse(id), menu.Id, 2);
                        foreach (VmenuModel menu2 in rootlist2)
                        {
                            menuhtml.Append("<tr>");
                            menuhtml.Append("<td></td>");
                            menuhtml.Append("<td align=\"center\">" + menu2.Menu_name + "</td>");
                            menuhtml.Append("<td></td>");
                            if (menu2.Disable == 1)
                            {
                                menuhtml.Append("<td align=\"center\"><i class=\"fa fa-check green\"></i></td>");
                            }
                            else
                            {
                                menuhtml.Append("<td align=\"center\"><i class=\"fa fa-close red\"></i></td>");
                            }
                            menuhtml.Append("<td align=\"center\"><a style=\"width: 60px;\" href=\"/Users/OpenRoleMenu/" + id + "/" + menu2.Id.ToString() + "/2/1\" class=\"btn btn-green\" data-toggle=\"doajax\" data-icon=\"check\" data-confirm-msg=\"确定要开通【" + menu2.Menu_name + "】所有权限吗？\"></a> <a style=\"width: 60px;\" href=\"/Users/OpenRoleMenu/" + id + "/" + menu2.Id.ToString() + "/2/0\" class=\"btn btn-red\" data-toggle=\"doajax\" data-icon=\"close\" data-confirm-msg=\"确定要关闭【" + menu.Menu_name + "】所有权限吗？\"></a></td>");
                            menuhtml.Append("</tr>");
                            List<VmenuModel> rootlist3 = _vmenuService.GetListByRoleidAndMenurootid(int.Parse(id), menu2.Id, 2);
                            foreach (VmenuModel menu3 in rootlist3)
                            {
                                menuhtml.Append("<tr>");
                                menuhtml.Append("<td></td>");
                                menuhtml.Append("<td></td>");
                                menuhtml.Append("<td align=\"center\">" + menu3.Menu_name + "</td>");
                                if (menu3.Disable == 1)
                                {
                                    menuhtml.Append("<td align=\"center\"><i class=\"fa fa-check green\"></i></td>");
                                }
                                else
                                {
                                    menuhtml.Append("<td align=\"center\"><i class=\"fa fa-close red\"></i></td>");
                                }
                                menuhtml.Append("<td align=\"center\"><a href=\"/Users/OpenRoleMenu/" + id + "/" + menu3.Id.ToString() + "/1/1\" class=\"btn btn-green\" data-toggle=\"doajax\" data-icon=\"check\"></a> <a href=\"/Users/OpenRoleMenu/" + id + "/" + menu3.Id.ToString() + "/1/0\" class=\"btn btn-red\" data-toggle=\"doajax\" data-icon=\"close\"></a></td>");
                                menuhtml.Append("</tr>");

                            }
                        }
                    }
                    ViewBag.menuhtml = menuhtml;
                }
                return View();

            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 根据menuid获取 用户权限
        /// </summary>
        /// <param name="meullist"></param>
        /// <param name="menuId"></param>
        /// <returns></returns>
        private string GetDisableHtml(List<RolemenuModel> rolemeullist, int menuId)
        {
            if (rolemeullist.Where(i => i.Menu_Id == menuId).Count() > 0)
            {
                if (rolemeullist.Where(i => i.Menu_Id == menuId).First().Disable == 1)
                {
                    return "<td align=\"center\"><i class=\"fa fa-check green\"></i></td>";
                }
                else
                {
                    return "<td align=\"center\"><i class=\"fa fa-close red\"></i></td>";
                }
            }
            else
            {
                return "<td></td>";
            }
        }

        /// <summary>
        /// 修改角色权限接口
        /// </summary>
        /// <param name="roleid"></param>
        /// <param name="menuid"></param>
        /// <param name="grade"></param>
        /// <returns></returns>
        [Route("Users/OpenRoleMenu/{roleid?}/{menuid?}/{grade?}/{disable?}")]
        public IActionResult OpenRoleMenu(string roleid, string menuid, string grade, string disable)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                List<MenuModel> list = new List<MenuModel>();
                Expression<Func<MenuModel, bool>> where = LinqUtil.True<MenuModel>();
                if (grade == "3")//根按钮
                {
                    where = where.AndAlso(i => i.Root_Id.ToString() == menuid || i.Id.ToString() == menuid);
                }
                else if (grade == "2")//二级按钮
                {
                    where = where.AndAlso(i => i.Parent_Id.ToString() == menuid || i.Id.ToString() == menuid);
                }
                else//最低级
                {
                    where = where.AndAlso(i => i.Id.ToString() == menuid);
                }
                list = _menuService.GetList(where);
                List<int> ids = new List<int>();
                foreach (MenuModel m in list)
                {
                    ids.Add(m.Id);
                }

                List<RolemenuModel> rlist = _rolemenuService.GetList().Where(i => ids.Contains(i.Menu_Id) && i.Role_Id == int.Parse(roleid)).ToList();
                foreach (RolemenuModel m in rlist)
                {
                    m.Disable = int.Parse(disable);
                }
                if (_rolemenuService.UpdateRange(rlist))
                {
                    _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)EnumUtil.OperationEnum.update, "修改角色信息顶级权限 roleid:" + roleid + ",menuid:" + menuid + ",disable:" + disable);
                    return Content(ReturnJsonHelp.BJUIajaxJson(200, "修改成功！", "UsersRoleMenu", "", "", false, "", ""));
                }
                else
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "修改失败！", "", "", "", false, "", ""));
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }


        /// <summary>
        /// 重置角色所有权限，新建并关闭所有权限
        /// </summary>
        /// <param name="id">roleid</param>
        /// <returns></returns>
        public IActionResult UpdateRolemenu(string id)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                //使用事务
                TransactionResult result = _rolemenuService.UpdateAll(int.Parse(id), 0);
                if (result.isError)
                {
                    _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)EnumUtil.OperationEnum.update, "重置角色[" + _roleService.GetById(Int32.Parse(id)).Role_name + "]所有权限，新建并关闭所有权限");
                    return Content(ReturnJsonHelp.BJUIajaxJson(200, "重置成功！", "", "", "", false, "", ""));
                }
                else
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "重置失败！" + result.message, "", "", "", false, "", ""));
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));

        }

        /// <summary>
        /// 按钮提交角色删除接口
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult RoleDelete(string id)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                Expression<Func<UsersModel, bool>> where = LinqUtil.True<UsersModel>();
                where = where.AndAlso(i => i.Role_id == int.Parse(id));
                if (_userService.GetList(where).Count() > 0)
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "删除失败,该角色下有用户！", "", "", "", false, "", ""));
                }
                else
                {
                    if (_roleService.DeleteById(int.Parse(id)))
                    {
                        return Content(ReturnJsonHelp.BJUIajaxJson(200, "删除成功！", "UsersRole", "", "", false, "", ""));
                    }
                    else
                    {
                        return Content(ReturnJsonHelp.BJUIajaxJson(300, "删除失败！", "", "", "", false, "", ""));
                    }
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 重置管理员所有权限，新建并开启所有权限
        /// </summary>
        /// <returns></returns>
        public IActionResult UpdateAdminmenu()
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                //使用事务
                TransactionResult result = _rolemenuService.UpdateAll(1, 1);
                if (result.isError)
                {
                    _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)EnumUtil.OperationEnum.update, "重置角色[管理员]所有权限，新建并开启所有权限");
                    return Content(ReturnJsonHelp.BJUIajaxJson(200, "重置成功！", "", "", "", false, "", ""));
                }
                else
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "重置失败！" + result.message, "", "", "", false, "", ""));
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }
        #endregion

        #region 平台记录
        /// <summary>
        /// 打开平台记录视图
        /// </summary>
        /// <param name="pagemodel"></param>
        /// <returns></returns>
        public IActionResult Loglist(PageModel pagemodel)
        {
            //获取Session信息并且返回前台
            SessionModel userSession = getUserSession();
            if (userSession != null)
            {
                if (string.IsNullOrEmpty(pagemodel.PageCurrent))
                    pagemodel.PageCurrent = "1";
                if (string.IsNullOrEmpty(pagemodel.PageSize))
                    pagemodel.PageSize = "30";
                ViewBag.SearchKeyWords = pagemodel.SearchKeyWords;
                ViewBag.PageSize = pagemodel.PageSize;
                ViewBag.PageCurrent = pagemodel.PageCurrent;
                ViewBag.OrderField = pagemodel.OrderField;
                ViewBag.OrderDirection = pagemodel.OrderDirection;

                Expression<Func<VlogModel, bool>> where = LinqUtil.True<VlogModel>();
                where = where.AndAlso(i => i.Login_name.Contains(pagemodel.SearchKeyWords) || i.User_name.Contains(pagemodel.SearchKeyWords) || i.Operation.Contains(pagemodel.SearchKeyWords) || i.Log_ip.Contains(pagemodel.SearchKeyWords) || i.Log_remark.Contains(pagemodel.SearchKeyWords) || i.Createtime.ToString("yyyy-MM-dd HH:mm:ss").Contains(pagemodel.SearchKeyWords));
                ViewBag.AllRecords = _vlogService.GetList(where).Count;
                ViewBag.Modellist = _vlogService.GetPageList(where, int.Parse(pagemodel.PageCurrent), int.Parse(pagemodel.PageSize), pagemodel.OrderField);

                return View();

            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        #endregion

        #region 注册
        /// <summary>
        /// 打开用户视图，用户列表
        /// </summary>
        /// <param name="pagemodel"></param>
        /// <returns></returns>
        public IActionResult Register()
        {

            return View();
        }

        /// <summary>
        ///表单提交用户编辑接口 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UserRegister")]
        public IActionResult UserRegister(UsersModel model)
        {

            UsersModel u = _userService.GetByLoginname(model.Login_name);
            if (u != null && model.Id == 0)
            {
                return Content(ReturnJsonHelp.BJUIajaxJson(300, "注册失败,登录账号已存在！", "", "", "", true, "", ""));
            }
            else
            {
                model.Createtime = DateTime.Now;
                if (model.User_pwd.Substring(0, 1) != "_")
                    model.User_pwd = CommonUtil.Md5(model.User_pwd);
                model.Disable = 0;//默认无登录权限
                model.Role_id = 3;//默认是游客
                if (_userService.Insert(model) > 0)
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(200, "注册用户 " + model.Login_name + " 成功！", "UsersIndex", "", "", true, "", ""));
                }
                else
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "注册用户 " + model.Login_name + " 失败！", "", "", "", false, "", ""));
                }

            }
        }
        #endregion
        #endregion
    }
}
